﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.UI.Modules;

using CharityGamesOnline.Modules.Event;
using CharityGamesOnline.Modules.Account;
using CharityGamesOnline.Modules.Common;

namespace CharityGamesOnline.Modules.Game
{
    public partial class GameDetail : CGOBase
    {
        protected int eventID = 0;

        public int EventDetailTabID
        {
            get
            {
                if (!Null.IsNull(Settings["EventDetailTabID"]))
                {
                    return Int32.Parse(Settings["EventDetailTabID"].ToString());
                }
                else
                    return TabId;
            }
        }

        public int PayTabID
        {
            get
            {
                if (!Null.IsNull(Settings["PayTabID"]))
                {
                    return Int32.Parse(Settings["PayTabID"].ToString());
                }
                else
                    return TabId;
            }
        }

        public int OrderListTabID
        {
            get
            {
                if (!Null.IsNull(Settings["OrderListTabID"]))
                {
                    return Int32.Parse(Settings["OrderListTabID"].ToString());
                }
                else
                    return TabId;
            }
        }

        public int EventID
        {
            get
            {
                if (eventID == 0)
                {
                    if ((Request.QueryString["EventID"] != null))
                    {
                        eventID = Int32.Parse(Request.QueryString["EventID"]);
                    }
                }
                return eventID;
            }
        }

        public bool TryGame
        {
            get
            {
                if (Request.QueryString["TryGame"] != null)
                {
                    return Boolean.Parse(Request.QueryString["TryGame"]);
                }
                else
                    return false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false)
            {
                BindData();                
            }
        }


        protected void btnGo_Click(object sender, EventArgs e)
        {           
            int gameID = Int32.Parse(((Button)sender).CommandArgument);
            StartGame(gameID);            
        }

        private void BindData()
        {
            if (!Page.IsPostBack && EventID > 0 && ValidEvent())
            {
                // get content 
                GameController ctrlGame = new GameController();
                List<GameInfo> lstGame = ctrlGame.GetGames(PortalId, EventID);
                if (lstGame.Count > 0)
                {
                    BindGame(lstGame[0]);
                    StartGame(lstGame[0].GameID);
                }
            }
            else
            {
                lbMessage.Text = Localization.GetString("errEventInvalid", LocalResourceFile);
            }
        }

        private bool ValidEvent()
        {
            EventController ctrlEvent = new EventController();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            EventInfo objEvent = ctrlEvent.GetEvent(PortalId, EventID);
            int intGamePlayed = ctrlEnroll.GetPlayedCount(PortalId, EventID,0,0,0);

            if(DateTime.Now > objEvent.DateEnd || DateTime.Now < objEvent.DateBegin )
            {
                return false;
            }
            else if (!objEvent.Signups || (objEvent.MaxEnrollment != 0 && intGamePlayed >= objEvent.MaxEnrollment))
            {
                return IsEnrolled(EventID);
            }
            else
            {
                return true;
            } 
        }

        private bool IsEnrolled(int eventID)
        {
            bool enrolled = false;
            GameController ctrlGame = new GameController();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            List<GameInfo> lstGame = ctrlGame.GetGames(PortalId, eventID);
            if (lstGame.Count > 0)
            {
                int gameID = lstGame[0].GameID;
                int enrollID = ctrlEnroll.GetUncompletedEnrollID(PortalId, eventID, gameID, UserId);
                if (enrollID != 0)
                {
                    enrolled = true;
                }
            }
            return enrolled;
        }

        private void BindGame(GameInfo e)
        {
            lbGameName.Text = e.Name;
            litDescription.Text = Server.HtmlDecode(e.Description);
            imgScreenShoot.Visible = false;
            if (e.ImageDisplay && !string.IsNullOrEmpty(e.ImageURL))
            {
                imgScreenShoot.Visible = true;
                imgScreenShoot.ImageUrl = GetIconUrl(e, "ImageURL");
                imgScreenShoot.Width = e.ImageWidth;
                imgScreenShoot.Height = e.ImageHeight;
            }

            btnGo.CommandArgument = e.GameID.ToString();
            btnGo.CommandName = EventID.ToString();            

            #region Bind Event Info

            EventController ctrlEvent = new EventController();
            EventInfo objEvent = ctrlEvent.GetEvent(PortalId, EventID);

            lnkEvent.Visible = false;
            lbEventName.Visible = false;

            if (objEvent != null)
            {
                lnkEvent.Text = objEvent.Name;
                lbEventName.Text = objEvent.Name;
                lbFee.Text = string.Format(Localization.GetString("lbFee", LocalResourceFile), objEvent.EnrollFee.ToString());

                if (EventDetailTabID > 0)
                {
                    lnkEvent.NavigateUrl = Globals.NavigateURL(EventDetailTabID, string.Empty, "EventID=" + EventID);
                    lnkEvent.Visible = true;
                }
                else
                {
                    lbEventName.Visible = true;
                }
            }
            #endregion
        }

        private void StartGame(int gameID)
        {
            bool bitGoToRecharge = false;
            GameController ctrlGame = new GameController();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            GameInfo objGame = ctrlGame.GetGame(gameID);

            EventController ctrlEvent = new EventController();
            EventInfo objEvent = ctrlEvent.GetEvent(PortalId, EventID);

            if (objGame != null && objEvent != null)
            {
                if (TryGame)
                {
                    Response.Redirect(Globals.NavigateURL(objGame.GameTabID, string.Empty, "TryGame=" + TryGame.ToString()));
                }
                else
                {
                    int enrollID = ctrlEnroll.GetUncompletedEnrollID(PortalId, objEvent.EventID, gameID, UserId);
                    //if there is no uncompleted enrollment, create a new one
                    if (enrollID == 0)
                    {
                        GameEnrollmentInfo objNewEnroll = new GameEnrollmentInfo();
                        objNewEnroll.PortalID = PortalId;
                        objNewEnroll.EventID = objEvent.EventID;
                        objNewEnroll.GameID = objGame.GameID;
                        objNewEnroll.UserID = UserId;
                        objNewEnroll.EnrollStatusID = (int)GameEnrollmentInfo.STATUS.ENROLLED;
                        objNewEnroll.EnrollFee = objEvent.EnrollFee;
                        objNewEnroll.StartTime = DateTime.Now;
                        objNewEnroll.ConnectCount = 0;

                        enrollID = ctrlEnroll.SaveEnrollment(objNewEnroll);
                    }

                    GameEnrollmentInfo objEnroll = ctrlEnroll.GetEnrollment(PortalId, enrollID);

                    if (objEnroll != null)
                    {
                        //if the enroll is not paid
                        if (objEnroll.EnrollStatusID == (int)GameEnrollmentInfo.STATUS.ENROLLED)
                        {
                            AccountController ctrlAccount = new AccountController();
                            AccountInfo objAccount = ctrlAccount.GetAccount(PortalId, UserId);
                            if (objAccount != null && objAccount.Token >= objEnroll.EnrollFee)
                            {
                                objAccount.Token = objAccount.Token - objEnroll.EnrollFee;
                                ctrlAccount.SaveAccount(objAccount);

                                AccountLogInfo objLog = new AccountLogInfo(objAccount);
                                objLog.Comment = string.Format(Localization.GetString("PayEnrollmentMsgFormat", LocalResourceFile),
                                                                    objEnroll.EnrollFee, objEvent.Name, objGame.Name);
                                ctrlAccount.SaveAccountLog(objLog);

                                objEnroll.EnrollStatusID = (int)GameEnrollmentInfo.STATUS.PAID;
                                ctrlEnroll.SaveEnrollment(objEnroll);
                            }
                            else
                            {
                                bitGoToRecharge = true;
                            }
                        }

                        if (bitGoToRecharge)
                        {
                            //Response.Redirect(Globals.NavigateURL(PayTabID, string.Empty, "GameEnrollmentID=" + objEnroll.EnrollmentID.ToString()));

                            PaymentController ctrlPayment = new PaymentController();
                            List<PaymentInfo> listPayment = ctrlPayment.GetPayments(PortalId, UserId, objEnroll.EnrollmentID, (int)PaymentInfo.STATUS.Processing);
                            if (listPayment.Count == 0)
                            {
                                Response.Redirect(Globals.NavigateURL(PayTabID, string.Empty, "GameEnrollmentID=" + objEnroll.EnrollmentID.ToString()));
                            }
                            else
                            {
                                Response.Redirect(Globals.NavigateURL(OrderListTabID, string.Empty, "GameEnrollmentID=" + objEnroll.EnrollmentID.ToString()));
                            }
                        }
                        else
                        {
                            Response.Redirect(Globals.NavigateURL(objGame.GameTabID, string.Empty, "GameEnrollmentID=" + objEnroll.EnrollmentID.ToString()));
                        }
                    }
                }
            } 
        }        
    }
}